package modes

import (
	"fmt"
	"time"
)

/*听课记录*/
type Records struct {
	Id        int64     `json:"cord_id" xorm:"id"`                 //听课记录id
	UId       int64     `json:"cord_uid" xorm:"uid"`               //学员ID
	SSId      int64     `json:"cord_s_id" xorm:"s_id"`             //课程Id（新增）
	SId       int64     `json:"cord_sid" xorm:"sid"`               //课程id (老版本课次更新后需要表中设置默认值0)
	CId       int64     `json:"cord_cid" xorm:"cid"`               //班型id
	Name      string    `json:"cord_name" xorm:"name"`             //课程名称
	StudyAt   int64     `json:"cord_study_at" xorm:"study_at"`     //学习时间
	LectureAt int64     `json:"cord_lecture_at" xorm:"lecture_at"` //听课时长 - 进度条时间
	TotalAt   int64     `json:"cord_total_at" xorm:"total_at"`     //总时长
	RUrl      string    `json:"cord_url" xorm:"url"`               //资源url
	LecCount  int64     `json:"cord_lec_count" xorm:"lec_count"`   //听课次数
	At        int64     `json:"cord_at" xorm:"at"`                 //创建时间
	CCId      int64     `json:"cord_cc_id" xorm:"cc_id"`           //课次Id （新增）
	Sign      int64     `json:"cord_sign" xorm:"sign"`             //标志 该课次最后一次标志 （新增）
	Dur       int64     `json:"cord_dur" xorm:"dur"`               //听课时长 - 定时器计数（新增）
	Typ       int64     `json:"cord_typ" xorm:"typ"`               //视频类型  1 录播 2是直播回放 (新增)
	Years     int64     `json:"cord_years" xorm:"years"`           //课程年份
	SName     []QSName  `json:"s_name" xorm:"-"`                   //课程名称
	SSName    []QSSName `json:"ss_name" xorm:"-"`                  //科目名称
	SaId      int64     `json:"s_id" xorm:"-"`
	SNameS    string    `json:"kc_name" xorm:"-"`
	SSSId     int64     `json:"ss_id" xorm:"-"`
	SSNameS   string    `json:"km_name" xorm:"-"`

	//ALTER TABLE record ADD dur int(10) unsigned   NOT NULL DEFAULT 0;  -- 听课时长 - 定时器计数（新增）
	//ALTER TABLE record ADD sign int(10) unsigned   NOT NULL DEFAULT 0;  -- 该课次最后一听课次标志 （新增）
	//ALTER TABLE record ADD cc_id int(10) unsigned   NOT NULL DEFAULT 0;  -- 课次Id （新增）
	//ALTER TABLE record ADD s_id int(10) unsigned   NOT NULL DEFAULT 0;  -- 课程Id（新增）
	//ALTER TABLE record ADD typ int(10) unsigned   NOT NULL DEFAULT 0;  -- 视频类型  1 录播 2是直播回放
	//ALTER TABLE record ADD years int(10) unsigned   NOT NULL DEFAULT 0;  -- 课程年份

}

func (this *Records) TableName() string {
	return "record"
}
func (this *Records) Save() (int64, error) {
	this.At = time.Now().Unix()
	this.LecCount++
	return Db(0).Insert(this)
}

func (this *Records) GetLog() (bool, error) {
	where := fmt.Sprintf("uid = %d and sid = %d", this.UId, this.SId)
	return Db(0).Where(where).Get(this)
}
func (this *Records) LastGet() (bool, error) {
	return Db(0).Desc("at").Limit(1).Get(this)
}

func (this *Records) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *Records) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *Records) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *Records) Counts(uid int64) (int64, error) {
	var val Records
	w := fmt.Sprintf("uid = %d ", uid)
	return Db(0).Where(w).Count(&val)
}
func (this *Records) Count(where string) (int64, error) {
	var val Records
	return Db(0).Where(where).Count(&val)
}

func (this *Records) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *Records) Set(field string) (int64, error) {
	where := fmt.Sprintf("uid = %d and sid = %d", this.UId, this.SId)
	return this.update(where, field)
}
func (this *Records) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("cc_id = %d and uid = %d ", this.CCId,this.UId)
	return this.update(where, field)
}

func (this *Records) where(fage, count, page int, where, field string) ([]Record, error) {
	list := make([]Record, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *Records) List(val *Pager) error {
	val.TName = this.TableName()
	w := fmt.Sprintf("uid = %d ", this.UId)
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}

func (this *Records) Lookups(val *Pager) error {
	list := make([]Records, 0)
	val.TName = "record"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.study_at", val.TName) // 时间排序
	default:
		field = fmt.Sprintf("%s.study_at", val.TName) // 状态
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).Count(this)
	err := Db(0).Table(val.TName).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
	}
	return err

}

type QSName struct {
	SId   int64  `json:"s_id" xorm:"id"`
	SName string `json:"s_name" xorm:"name"`
	ClaUrl string `json:"cla_url" xorm:"course_url"`
}

type QSSName struct {
	SId   int64  `json:"s_id" xorm:"id"`
	SName string `json:"s_name" xorm:"name"`
}

func (this *Records) NotesList(val *Pager) error {
	list := make([]Records, 0)
	val.TName = "record"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.at", val.TName) // 排序
	default:
		field = fmt.Sprintf("%s.at", val.TName) // 排序
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(0).Table(val.TName).
		Where(val.ToWhere()).
		Count(this)
	err := Db(0).Table(val.TName).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
	}
	// 这是课次的 list ， 取得 这些 课次的 课程名称 和 科目名称
	plays := []int64{}
	for n, _ := range list {
		plays = append(plays, list[n].SSId)
	}
	// 从上面的 list 中 提取 课程Ids 通过in语句得到所有课程的名称
	plys, _ := (&QqSName{}).RecordClassName(plays)
	for _, it := range plys {
		for n, _ := range list {
			if list[n].SSId == it.SId {
				list[n].SaId = it.SId
				list[n].SNameS = it.SName
			}
		}
	}
	kmds, _ := (&SubSubjects{}).SubjectSIds(plays)
	for _, it := range kmds {
		for n, _ := range list {
			if list[n].SSId == it.SId {
				list[n].SSSId = it.Id
				list[n].SSNameS = it.Name

			}
		}
	}
	return err
}
func (this *Subjects) RecordClassName(sid int64) ([]QSName, error) {
	swhere := fmt.Sprintf("id = %d", sid)
	list := make([]QSName, 0)
	return list, Db(0).Table("subject").Cols("id,name").Where(swhere).Find(&list)
}
func (this *Subjects) RecordClassNName(sid int64) ([]QSSName, error) {
	swhere := fmt.Sprintf("id = %d - %d%%100000", sid, sid)
	list := make([]QSSName, 0)
	return list, Db(0).Table("subject").Cols("id,name").Where(swhere).Find(&list)
}
func (this *Records) GetTime(uid int64) ([]int64, error) {
	swhere := fmt.Sprintf("uid  = %d ", uid)
	var dl []int64
	err := Db(0).Table("record").Cols("at").Where(swhere).Desc("at").Limit(1).Find(&dl)
	return dl, err
}
func (this *Records) CountTime(uid, stim int64) (float64, error) {
	swhere := fmt.Sprintf("uid  = %d  and at >= %d ", uid, stim)
	return Db(0).Table("record").Where(swhere).Sum(&Records{}, "dur")
}
func (this *Records) SubjectLastRecord(uid, sid int64) ([]Records, error) {
	list := make([]Records, 0)
	swhere := fmt.Sprintf("uid  = %d  and s_id > %d and s_id < %d ", uid, sid, sid+100000)
	err := Db(0).Table("record").Where(swhere).Desc("at").Limit(1).Find(&list)
	for i, row := range list {
		var sus Subjects
		list[i].SName, _ = sus.RecordClassName(row.SSId)
		list[i].SSName, _ = sus.RecordClassNName(row.SSId)
	}
	return list, err
}
